package controller {
	import model.FlashVarsProxy;	
	
	import org.puremvc.as3.multicore.utilities.startupmanager.model.RetryParameters;	
	import org.puremvc.as3.multicore.utilities.startupmanager.model.RetryPolicy;	
	
	import view.StartupSimpleDemoMediator;	
	
	import org.puremvc.as3.multicore.utilities.startupmanager.model.StartupMonitorProxy;	
	import org.puremvc.as3.multicore.utilities.startupmanager.controller.StartupResourceFailedCommand;	
	import org.puremvc.as3.multicore.utilities.startupmanager.controller.StartupResourceLoadedCommand;	
	import org.puremvc.as3.multicore.utilities.startupmanager.model.StartupResourceProxy;	
	
	import model.DynamicEntityProxy;	
	
	import org.puremvc.as3.multicore.interfaces.INotification;	
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;	
	
	/**
	 * @author Darshan Sawardekar
	 */
	public class StartupSimpleDemoStartupCommand extends SimpleCommand {
		
		override public function execute(note:INotification):void {
			var app:StartupSimpleDemo = note.getBody() as StartupSimpleDemo;
			var monitorProxy:StartupMonitorProxy = new StartupMonitorProxy();
			var flashVarsProxy:FlashVarsProxy = new FlashVarsProxy(app.parameters);
			
			flashVarsProxy.setDefault("resourceCount", 10);
			flashVarsProxy.setDefault("maxDelayMSecs", 1000);
			flashVarsProxy.setDefault("probabilityOfFault", 0.5);
			
			facade.registerProxy(monitorProxy);
			facade.registerProxy(flashVarsProxy);
			
			facade.registerMediator(new StartupSimpleDemoMediator(note.getBody() as StartupSimpleDemo));
			
			var prevResourceProxy:StartupResourceProxy;
			var resourceCount:int = int(flashVarsProxy.getParam("resourceCount"));
			
			for (var i:int; i < resourceCount; i++) {
				var entityProxy:DynamicEntityProxy = new DynamicEntityProxy();
				
				entityProxy.maxDelayMSecs = parseInt(String(flashVarsProxy.getParam("maxDelayMSecs")));
				entityProxy.probabilityOfFault = parseFloat(String(flashVarsProxy.getParam("probabilityOfFault")));
				
				var resourceProxy:StartupResourceProxy = new StartupResourceProxy(entityProxy.entitySRName, entityProxy);
				resourceProxy.retryPolicy = new RetryPolicy(new RetryParameters(1000, 0.5, 15));
				
				facade.registerProxy(entityProxy);
				facade.registerProxy(resourceProxy);
				
				if (prevResourceProxy != null) {
					resourceProxy.requires = [prevResourceProxy];
				}
				
				prevResourceProxy = resourceProxy;
				
				facade.registerCommand(entityProxy.loadedNotification, StartupResourceLoadedCommand);
				facade.registerCommand(entityProxy.failedNotification, StartupResourceFailedCommand);
				
				monitorProxy.addResource(resourceProxy);
			}
			
			monitorProxy.loadResources();
		}
	}
}
